#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>

using namespace std;

const int BUFFER_SIZE = 1024;

int main(int argc, char* argv[])
{
    if (argc <= 2)
    {
        cerr << "Usage: " << argv[0] << " <server> <port>" << endl;
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi(argv[2]);

    struct sockaddr_in server_address;
    memset(&server_address, 0, sizeof(server_address));
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(port);
    inet_pton(AF_INET, ip, &server_address.sin_addr);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(sockfd >= 0);

    // 设置发送缓冲区大小
    int sendbuf = atoi(argv[3]);
    int len = sizeof(sendbuf);
    setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendbuf, len);
    getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendbuf, (socklen_t*)&len);
    cout << "The send buffer size after setting is: " << sendbuf << endl;
    
    if ( connect(sockfd, (struct sockaddr*)&server_address, sizeof(server_address)) < 0)
    {
        cerr << "Connection failed: " << strerror(errno) << endl;
        close(sockfd);
        return 1;
    }
    else
    {
        char buffer[BUFFER_SIZE];
        memset(buffer, 'a', BUFFER_SIZE);
        send(sockfd, buffer, BUFFER_SIZE, 0);
    }

    close (sockfd);

    return 0;
}